home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / CLIENT.PY < prev    next >
Encoding:
Python Source  |  2000-10-16  |  21.8 KB  |  642 lines

  1. #!/bin/sh
  2. """:"
  3. exec python $0 ${1+"$@"}
  4. """
  5. #"
  6. ##############################################################################
  7. # Zope Public License (ZPL) Version 1.0
  8. # -------------------------------------
  9. # Copyright (c) Digital Creations.  All rights reserved.
  10. # This license has been certified as Open Source(tm).
  11. # Redistribution and use in source and binary forms, with or without
  12. # modification, are permitted provided that the following conditions are
  13. # met:
  14. # 1. Redistributions in source code must retain the above copyright
  15. #    notice, this list of conditions, and the following disclaimer.
  16. # 2. Redistributions in binary form must reproduce the above copyright
  17. #    notice, this list of conditions, and the following disclaimer in
  18. #    the documentation and/or other materials provided with the
  19. #    distribution.
  20. # 3. Digital Creations requests that attribution be given to Zope
  21. #    in any manner possible. Zope includes a "Powered by Zope"
  22. #    button that is installed by default. While it is not a license
  23. #    violation to remove this button, it is requested that the
  24. #    attribution remain. A significant investment has been put
  25. #    into Zope, and this effort will continue if the Zope community
  26. #    continues to grow. This is one way to assure that growth.
  27. # 4. All advertising materials and documentation mentioning
  28. #    features derived from or use of this software must display
  29. #    the following acknowledgement:
  30. #      "This product includes software developed by Digital Creations
  31. #      for use in the Z Object Publishing Environment
  32. #      (http://www.zope.org/)."
  33. #    In the event that the product being advertised includes an
  34. #    intact Zope distribution (with copyright and license included)
  35. #    then this clause is waived.
  36. # 5. Names associated with Zope or Digital Creations must not be used to
  37. #    endorse or promote products derived from this software without
  38. #    prior written permission from Digital Creations.
  39. # 6. Modified redistributions of any form whatsoever must retain
  40. #    the following acknowledgment:
  41. #      "This product includes software developed by Digital Creations
  42. #      for use in the Z Object Publishing Environment
  43. #      (http://www.zope.org/)."
  44. #    Intact (re-)distributions of any official Zope release do not
  45. #    require an external acknowledgement.
  46. # 7. Modifications are encouraged but must be packaged separately as
  47. #    patches to official Zope releases.  Distributions that do not
  48. #    clearly separate the patches from the original work must be clearly
  49. #    labeled as unofficial distributions.  Modifications which do not
  50. #    carry the name Zope may be packaged in any form, as long as they
  51. #    conform to all of the clauses above.
  52. # Disclaimer
  53. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  54. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  55. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  56. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  57. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  58. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  59. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  60. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  61. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  62. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  63. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  64. #   SUCH DAMAGE.
  65. # This software consists of contributions made by Digital Creations and
  66. # many individuals on behalf of Digital Creations.  Specific
  67. # attributions are listed in the accompanying credits file.
  68. ##############################################################################
  69. """Bobo call interface
  70.  
  71. This module provides tools for accessing web objects as if they were 
  72. functions or objects with methods.  It also provides a simple call function 
  73. that allows one to simply make a single web request.
  74.  
  75.   Function -- Function-like objects that return both header and body
  76.               data when called.
  77.  
  78.   Object -- Treat a URL as a web object with methods
  79.  
  80.   call -- Simple interface to call a remote function.
  81.  
  82. The module also provides a command-line interface for calling objects.
  83.  
  84. """
  85. __version__='$Revision: 1.34.12.5 $'[11:-2]
  86.  
  87. import sys, regex, socket, mimetools
  88. from httplib import HTTP
  89. from os import getpid
  90. from time import time
  91. from random import random
  92. from base64 import encodestring
  93. from urllib import urlopen, quote
  94. from types import FileType, ListType, DictType, TupleType
  95. from string import strip, split, atoi, join, rfind, translate, maketrans, replace, lower
  96. from urlparse import urlparse
  97.  
  98. class Function:
  99.     username=None
  100.     password=None
  101.     method=None
  102.     timeout=60
  103.  
  104.     def __init__(self,url,
  105.                  arguments=(),method=None,username=None,password=None,
  106.                  timeout=None,
  107.                  **headers):
  108.         while url[-1:]=='/': url=url[:-1]
  109.         self.url=url
  110.         self.headers=headers
  111.         if not headers.has_key('Host') and not headers.has_key('host'):
  112.             headers['Host']=urlparse(url)[1]
  113.         self.func_name=url[rfind(url,'/')+1:]
  114.         self.__dict__['__name__']=self.func_name
  115.         self.func_defaults=()
  116.         
  117.         self.args=arguments
  118.  
  119.         if method is not None: self.method=method
  120.         if username is not None: self.username=username
  121.         if password is not None: self.password=password
  122.         if timeout is not None: self.timeout=timeout
  123.  
  124.         if urlregex.match(url) >= 0:
  125.             host,port,rurl=urlregex.group(1,2,3)
  126.             if port: port=atoi(port[1:])
  127.             else: port=80
  128.             self.host=host
  129.             self.port=port
  130.             rurl=rurl or '/'
  131.             self.rurl=rurl
  132.         else: raise ValueError, url
  133.  
  134.     def __call__(self,*args,**kw):
  135.         method=self.method
  136.         if method=='PUT' and len(args)==1 and not kw:
  137.             query=[args[0]]
  138.             args=()
  139.         else:
  140.             query=[]
  141.         for i in range(len(args)):
  142.             try:
  143.                 k=self.args[i]
  144.                 if kw.has_key(k): raise TypeError, 'Keyword arg redefined'
  145.                 kw[k]=args[i]
  146.             except IndexError:    raise TypeError, 'Too many arguments'
  147.  
  148.         headers={}
  149.         for k, v in self.headers.items(): headers[translate(k,dashtrans)]=v
  150.         method=self.method
  151.         if headers.has_key('Content-Type'):
  152.             content_type=headers['Content-Type']
  153.             if content_type=='multipart/form-data':
  154.                 return self._mp_call(kw)
  155.         else:
  156.             content_type=None
  157.             if not method or method=='POST':
  158.                 for v in kw.values():
  159.                     if hasattr(v,'read'): return self._mp_call(kw)
  160.                 
  161.         can_marshal=type2marshal.has_key
  162.         for k,v in kw.items():
  163.             t=type(v)
  164.             if can_marshal(t): q=type2marshal[t](k,v)
  165.             else: q='%s=%s' % (k,quote(v))
  166.             query.append(q)
  167.  
  168.         url=self.rurl
  169.         if query:
  170.             query=join(query,'&')
  171.             method=method or 'POST'
  172.             if method == 'PUT':
  173.                 headers['Content-Length']=str(len(query))
  174.             if method != 'POST':
  175.                 url="%s?%s" % (url,query)
  176.                 query=''
  177.             elif not content_type:
  178.                 headers['Content-Type']='application/x-www-form-urlencoded'
  179.                 headers['Content-Length']=str(len(query))
  180.         else: method=method or 'GET'
  181.  
  182.         if (self.username and self.password and
  183.             not headers.has_key('Authorization')):
  184.             headers['Authorization']=(
  185.                 "Basic %s" %
  186.                 replace(encodestring('%s:%s' % (self.username,self.password)),
  187.                      '\012',''))
  188.         
  189.         try:
  190.             h=HTTP()
  191.             h.connect(self.host, self.port)
  192.             h.putrequest(method, self.rurl)
  193.             for hn,hv in headers.items():
  194.                 h.putheader(translate(hn,dashtrans),hv)
  195.             h.endheaders()
  196.             if query: h.send(query)
  197.             ec,em,headers=h.getreply()
  198.             response     =h.getfile().read()
  199.         except:
  200.             raise NotAvailable, RemoteException(
  201.                 NotAvailable,sys.exc_info()[1],self.url,query)
  202.         if (ec - (ec % 100)) == 200:
  203.             return (headers,response)
  204.         self.handleError(query, ec, em, headers, response)
  205.  
  206.  
  207.     def handleError(self, query, ec, em, headers, response):
  208.         try:    v=headers.dict['bobo-exception-value']
  209.         except: v=ec
  210.         try:    f=headers.dict['bobo-exception-file']
  211.         except: f='Unknown'
  212.         try:    l=headers.dict['bobo-exception-line']
  213.         except: l='Unknown'
  214.         try:    t=exceptmap[headers.dict['bobo-exception-type']]
  215.         except:
  216.             if   ec >= 400 and ec < 500: t=NotFound
  217.             elif ec == 503:              t=NotAvailable
  218.             else:                        t=ServerError
  219.         raise t, RemoteException(t,v,f,l,self.url,query,ec,em,response)
  220.         
  221.  
  222.     
  223.  
  224.     def _mp_call(self,kw,
  225.                 type2suffix={
  226.                     type(1.0): ':float',
  227.                     type(1):   ':int',
  228.                     type(1L):  ':long',
  229.                     type([]):  ':list',
  230.                     type(()):  ':tuple',
  231.                     }
  232.                 ):
  233.         # Call a function using the file-upload protcol
  234.  
  235.         # Add type markers to special values:
  236.         d={}
  237.         special_type=type2suffix.has_key
  238.         for k,v in kw.items():
  239.             if ':' not in k:
  240.                 t=type(v)
  241.                 if special_type(t): d['%s%s' % (k,type2suffix[t])]=v
  242.                 else: d[k]=v
  243.             else: d[k]=v
  244.  
  245.         rq=[('POST %s HTTP/1.0' % self.rurl),]
  246.         for n,v in self.headers.items():
  247.             rq.append('%s: %s' % (n,v))
  248.         if self.username and self.password:
  249.             c=replace(encodestring('%s:%s' % (self.username,self.password)),'\012','')
  250.             rq.append('Authorization: Basic %s' % c)
  251.         rq.append(MultiPart(d).render())
  252.         rq=join(rq,'\r\n')   
  253.  
  254.         try:
  255.             sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  256.             sock.connect((self.host,self.port))
  257.             sock.send(rq)
  258.             reply=sock.makefile('rb')
  259.             sock=None
  260.             line=reply.readline()
  261.  
  262.             try:
  263.                 [ver, ec, em] = split(line, None, 2)
  264.             except ValueError:
  265.                 raise 'BadReply','Bad reply from server: '+line
  266.             if ver[:5] != 'HTTP/':
  267.                 raise 'BadReply','Bad reply from server: '+line
  268.  
  269.             ec=atoi(ec)
  270.             em=strip(em)
  271.             headers=mimetools.Message(reply,0)
  272.             response=reply.read()
  273.         finally:
  274.           if 0:
  275.             raise NotAvailable, (
  276.                 RemoteException(NotAvailable,sys.exc_info()[1],
  277.                                 self.url,'<MultiPart Form>'))
  278.                 
  279.         if ec==200: return (headers,response)
  280.         self.handleError('', ec, em, headers, response)
  281.  
  282. class Object:
  283.     """Surrogate object for an object on the web"""
  284.     username=None
  285.     password=None
  286.     method=None
  287.     timeout=None
  288.     special_methods= 'GET','POST','PUT'
  289.  
  290.     def __init__(self, url,
  291.                  method=None,username=None,password=None,
  292.                  timeout=None,
  293.                  **headers):
  294.         self.url=url
  295.         self.headers=headers
  296.         if not headers.has_key('Host') and not headers.has_key('host'):
  297.             headers['Host']=urlparse(url)[1]
  298.         if method is not None: self.method=method
  299.         if username is not None: self.username=username
  300.         if password is not None: self.password=password
  301.         if timeout is not None: self.timeout=timeout
  302.  
  303.     def __getattr__(self, name):
  304.         if name in self.special_methods:
  305.             method=name
  306.             url=self.url
  307.         else:
  308.             method=self.method
  309.             url="%s/%s" % (self.url, name)
  310.  
  311.         f=Function(url,
  312.                    method=method,
  313.                    username=self.username,
  314.                    password=self.password,
  315.                    timeout=self.timeout)
  316.  
  317.         f.headers=self.headers
  318.  
  319.         return f
  320.  
  321. def call(url,username=None, password=None, **kw):
  322.     
  323.     return apply(Function(url,username=username, password=password), (), kw)
  324.  
  325. ##############################################################################
  326. # Implementation details below here
  327.  
  328. urlregex=regex.compile('http://\([^:/]+\)\(:[0-9]+\)?\(/.+\)?', regex.casefold)
  329.  
  330. dashtrans=maketrans('_','-')
  331.  
  332. def marshal_float(n,f): return '%s:float=%s' % (n,f)
  333. def marshal_int(n,f):   return '%s:int=%s' % (n,f)
  334. def marshal_long(n,f):  return ('%s:long=%s' % (n,f))[:-1]
  335.  
  336. sample_regex=regex.compile('')
  337. def marshal_regex(n,r):
  338.     if r.translate is sample_regex.translate:
  339.         t='Regex'
  340.     elif r.translate is regex.casefold:
  341.         t='regex'
  342.     else:
  343.         raise ValueError, 'regular expression used unsupported translation'
  344.     return "%s:%s=%s" % (n,t,quote(r.givenpat))
  345.  
  346. def marshal_list(n,l,tname='list', lt=type([]), tt=type(())):
  347.     r=[]
  348.     for v in l:
  349.         t=type(v)
  350.         if t is lt or t is tt:
  351.             raise TypeError, 'Invalid recursion in data to be marshaled.'
  352.         r.append(marshal_whatever("%s:%s" % (n,tname) ,v))
  353.     
  354.     return join(r,'&')
  355.  
  356. def marshal_tuple(n,l):
  357.     return marshal_list(n,l,'tuple')
  358.     
  359. type2marshal={
  360.     type(1.0):                  marshal_float,
  361.     type(1):                    marshal_int,
  362.     type(1L):                   marshal_long,
  363.     type(regex.compile('')):    marshal_regex,
  364.     type([]):                   marshal_list,
  365.     type(()):                   marshal_tuple,
  366.     }
  367.  
  368. def marshal_whatever(k,v):
  369.     try: q=type2marshal[type(v)](k,v)
  370.     except KeyError: q='%s=%s' % (k,quote(str(v)))
  371.     return q
  372.  
  373. def querify(items):
  374.     query=[]
  375.     for k,v in items: query.append(marshal_whatever(k,v))
  376.  
  377.     return query and join(query,'&') or ''
  378.  
  379. NotFound     ='bci.NotFound'
  380. InternalError='bci.InternalError'
  381. BadRequest   ='bci.BadRequest'
  382. Unauthorized ='bci.Unauthorized'
  383. ServerError  ='bci.ServerError'
  384. NotAvailable ='bci.NotAvailable'
  385.  
  386. exceptmap   ={'AttributeError'   :AttributeError,
  387.               'BadRequest'       :BadRequest,
  388.               'EOFError'         :EOFError,
  389.               'IOError'          :IOError,
  390.               'ImportError'      :ImportError,
  391.               'IndexError'       :IndexError,
  392.               'InternalError'    :InternalError,
  393.               'KeyError'         :KeyError,
  394.               'MemoryError'      :MemoryError,
  395.               'NameError'        :NameError,
  396.               'NotAvailable'     :NotAvailable,
  397.               'NotFound'         :NotFound,
  398.               'OverflowError'    :OverflowError,
  399.               'RuntimeError'     :RuntimeError,
  400.               'ServerError'      :ServerError,
  401.               'SyntaxError'      :SyntaxError,
  402.               'SystemError'      :SystemError,
  403.               'SystemExit'       :SystemExit,
  404.               'TypeError'        :TypeError,
  405.               'Unauthorized'     :Unauthorized,
  406.               'ValueError'       :ValueError,
  407.               'ZeroDivisionError':ZeroDivisionError}
  408.  
  409.  
  410. class RemoteException:
  411.  
  412.     def __init__(self,etype=None,evalue=None,efile=None,eline=None,url=None,
  413.                  query=None,http_code=None,http_msg=None, http_resp=None):
  414.         """Contains information about an exception which
  415.            occurs in a remote method call"""
  416.         self.exc_type    =etype
  417.         self.exc_value   =evalue
  418.         self.exc_file    =efile
  419.         self.exc_line    =eline
  420.         self.url         =url
  421.         self.query       =query
  422.         self.http_code   =http_code
  423.         self.http_message=http_msg
  424.         self.response    =http_resp
  425.  
  426.     def __repr__(self):
  427.         return '%s (File: %s Line: %s)\n%s %s for %s' % (
  428.                 self.exc_value,self.exc_file,self.exc_line,
  429.                 self.http_code,self.http_message,self.url)
  430.  
  431.  
  432.  
  433. class MultiPart:
  434.     def __init__(self,*args):
  435.         c=len(args)
  436.         if c==1:    name,val=None,args[0]
  437.         elif c==2:  name,val=args[0],args[1]
  438.         else:       raise ValueError, 'Invalid arguments'
  439.  
  440.  
  441.         h={'Content-Type':              {'_v':''},
  442.            'Content-Transfer-Encoding': {'_v':''},
  443.            'Content-Disposition':       {'_v':''},}
  444.         dt=type(val)
  445.         b=t=None
  446.  
  447.         if dt==DictType:
  448.             t=1
  449.             b=self.boundary()
  450.             d=[]
  451.             h['Content-Type']['_v']='multipart/form-data; boundary=%s' % b
  452.             for n,v in val.items():
  453.                 d.append(MultiPart(n,v))
  454.  
  455.         elif (dt==ListType) or (dt==TupleType):
  456.             raise ValueError, 'Sorry, nested multipart is not done yet!'
  457.  
  458.         elif dt==FileType or hasattr(val,'read'):
  459.             if hasattr(val,'name'):
  460.                 fn=replace(val.name, '\\', '/')
  461.                 fn=fn[(rfind(fn,'/')+1):]
  462.                 ex=lower(fn[(rfind(fn,'.')+1):])
  463.                 if self._extmap.has_key(ex):
  464.                     ct=self._extmap[ex]
  465.                 else:
  466.                     ct=self._extmap['']
  467.             else:
  468.                 fn=''
  469.                 ct=self._extmap[None]
  470.             if self._encmap.has_key(ct): ce=self._encmap[ct]
  471.             else: ce=''
  472.  
  473.             h['Content-Disposition']['_v']      ='form-data'
  474.             h['Content-Disposition']['name']    ='"%s"' % name
  475.             h['Content-Disposition']['filename']='"%s"' % fn
  476.             h['Content-Transfer-Encoding']['_v']=ce
  477.             h['Content-Type']['_v']             =ct
  478.             d=[]
  479.             l=val.read(8192)
  480.             while l:
  481.                 d.append(l)
  482.                 l=val.read(8192)
  483.         else:
  484.             h['Content-Disposition']['_v']='form-data'
  485.             h['Content-Disposition']['name']='"%s"' % name
  486.             d=[str(val)]
  487.  
  488.         self._headers =h
  489.         self._data    =d
  490.         self._boundary=b
  491.         self._top     =t
  492.  
  493.  
  494.     def boundary(self):
  495.         return '%s_%s_%s' % (int(time()), getpid(), int(random()*1000000000))
  496.  
  497.  
  498.     def render(self):
  499.         h=self._headers
  500.         s=[]
  501.  
  502.         if self._top:
  503.             for n,v in h.items():
  504.                 if v['_v']:
  505.                     s.append('%s: %s' % (n,v['_v']))
  506.                     for k in v.keys():
  507.                         if k != '_v': s.append('; %s=%s' % (k, v[k]))
  508.                     s.append('\r\n')
  509.             p=[]
  510.             t=[]
  511.             b=self._boundary
  512.             for d in self._data: p.append(d.render())
  513.             t.append('--%s\n' % b)
  514.             t.append(join(p,'\n--%s\n' % b))
  515.             t.append('\n--%s--\n' % b)
  516.             t=join(t,'')
  517.             s.append('Content-Length: %s\r\n\r\n' % len(t))
  518.             s.append(t)
  519.             return join(s,'')
  520.  
  521.         else:
  522.             for n,v in h.items():
  523.                 if v['_v']:
  524.                     s.append('%s: %s' % (n,v['_v']))
  525.                     for k in v.keys():
  526.                         if k != '_v': s.append('; %s=%s' % (k, v[k]))
  527.                     s.append('\r\n')
  528.             s.append('\r\n')
  529.  
  530.             if self._boundary:
  531.                 p=[]
  532.                 b=self._boundary
  533.                 for d in self._data: p.append(d.render())
  534.                 s.append('--%s\n' % b)
  535.                 s.append(join(p,'\n--%s\n' % b))
  536.                 s.append('\n--%s--\n' % b)
  537.                 return join(s,'')
  538.             else:
  539.                 return join(s+self._data,'')
  540.  
  541.  
  542.     _extmap={'':     'text/plain',
  543.              'rdb':  'text/plain',
  544.              'html': 'text/html',
  545.              'dtml': 'text/html',
  546.              'htm':  'text/html',
  547.              'dtm':  'text/html',
  548.              'gif':  'image/gif',
  549.              'jpg':  'image/jpeg',
  550.              'exe':  'application/octet-stream',
  551.              None :  'application/octet-stream',
  552.              }
  553.  
  554.     _encmap={'image/gif': 'binary',
  555.              'image/jpg': 'binary',
  556.              'application/octet-stream': 'binary',
  557.              }
  558.  
  559.  
  560. def ErrorTypes(code):
  561.     if code >= 400 and code < 500: return NotFound
  562.     if code >= 500 and code < 600: return ServerError
  563.     return 'HTTP_Error_%s' % code
  564.  
  565. usage="""
  566. Usage: %s [-u username:password] url [name=value ...]
  567.  
  568. where url is the web resource to call.
  569.  
  570. The -u option may be used to provide a user name and password.
  571.  
  572. Optional arguments may be provides as name=value pairs.
  573.  
  574. In a name value pair, if a name ends in ":file", then the value is
  575. treated as a file name and the file is send using the file-upload
  576. protocol.   If the file name is "-", then data are taken from standard
  577. input.
  578.  
  579. The body of the response is written to standard output.
  580. The headers of the response are written to standard error.
  581.  
  582. """ % sys.argv[0]
  583.  
  584. def main():
  585.     import getopt
  586.     from string import split
  587.  
  588.     user=None
  589.  
  590.     try:
  591.         optlist, args = getopt.getopt(sys.argv[1:],'u:')
  592.         url=args[0]
  593.         u =filter(lambda o: o[0]=='-u', optlist)
  594.         if u:
  595.             [user, pw] = split(u[0][1],':')
  596.  
  597.         kw={}
  598.         for arg in args[1:]:
  599.             [name,v]=split(arg,'=')
  600.             if name[-5:]==':file':
  601.                 name=name[:-5]
  602.                 if v=='-': v=sys.stdin
  603.                 else: v=open(v, 'rb')
  604.             kw[name]=v
  605.  
  606.     except:
  607.         print usage
  608.         sys.exit(1)
  609.         
  610.     # The "main" program for this module
  611.     f=Function(url)
  612.     if user: f.username, f.password = user, pw
  613.     headers, body = apply(f,(),kw)
  614.     sys.stderr.write(join(map(lambda h: "%s: %s\n" % h, headers.items()),"")
  615.                      +"\n\n")
  616.     print body
  617.  
  618.  
  619. if __name__ == "__main__":
  620.     main()
  621.